//
//  SmallDecisionsActionSheetViewController.m
//  SmallDecisions
//
//  Created by 李付雄 on 2025/6/14.
//

#import "SmallDecisionsActionSheetViewController.h"
#define MarginSpace 15.0
#define CellRowHeight 55.0

@interface SmallDecisionsActionSheetViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, copy) NSArray  *list;
@property (nonatomic, copy) NSString *cancelText;

@property (nonatomic, copy) void(^selectedBlock)(NSInteger index);
@property (nonatomic, copy) void(^cancelBlock)(void);
@property (nonatomic,   copy) NSString *(^objectToTextConverter)(id object);

@property (nonatomic, copy) NSString *sheetTitle;


@end
@implementation SmallDecisionsActionSheetViewController

+ (SmallDecisionsActionSheetViewController *)showActionSheetWtihTitle:(NSString * _Nullable)title
                                                              list:(NSArray *)list
                                                        cancelText:(NSString * _Nullable)cancelText
                                                     selectedBlock:(void(^ _Nullable)(NSInteger index))selectedBlock
                                                       cancelBlock:(void(^ _Nullable)(void))cancelBlock
                                             objectToTextConverter:(NSString *(^)(id data))objectToTextConverter {
    
    SmallDecisionsActionSheetViewController *actionSheetVC = [[SmallDecisionsActionSheetViewController alloc] init];
    actionSheetVC.sheetTitle = title;
    actionSheetVC.list = list;
    actionSheetVC.cancelText = cancelText;
    actionSheetVC.selectedBlock = selectedBlock;
    actionSheetVC.cancelBlock = cancelBlock;
    actionSheetVC.objectToTextConverter = objectToTextConverter;
    actionSheetVC.view.backgroundColor = [UIColor clearColor];
    [SmallDecisionsNavigatorManager presentViewController:actionSheetVC animationType:SmallDecisionsAnimationTypeFullPop];
    
    return actionSheetVC;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hideSmallDecisionsNavigationBar];
    [self judgeSmallDecisionsActionSheetVCWithShow:YES];
}


- (void)hideSmallDecisionsNavigationBar {
    if (@available(iOS 15.0, *)) {
        UINavigationBarAppearance *barStandardAppearance = [UINavigationBarAppearance new];
        [barStandardAppearance configureWithOpaqueBackground];
        barStandardAppearance.shadowColor     = [UIColor clearColor];
        barStandardAppearance.shadowImage     = nil;
        barStandardAppearance.backgroundColor = [UIColor clearColor];
        barStandardAppearance.backgroundImage = [UIImage imageWithColor:[UIColor clearColor]];
        barStandardAppearance.titleTextAttributes = @{ NSForegroundColorAttributeName : SmallDecisionsThemeFontColor, NSFontAttributeName: [UIFont systemFontOfSize:17 weight:UIFontWeightMedium]};
        self.navigationController.navigationBar.standardAppearance   = barStandardAppearance;
        
        UINavigationBarAppearance *barScrollEdgeAppearance = [UINavigationBarAppearance new];
        [barScrollEdgeAppearance configureWithOpaqueBackground];
        barScrollEdgeAppearance.backgroundColor = [UIColor clearColor];
        barScrollEdgeAppearance.shadowImage = [UIImage new];
        barScrollEdgeAppearance.shadowColor = [UIColor clearColor];
        barScrollEdgeAppearance.backgroundImage = [UIImage imageWithColor:[UIColor clearColor]];
        barScrollEdgeAppearance.titleTextAttributes = @{ NSForegroundColorAttributeName : SmallDecisionsThemeFontColor, NSFontAttributeName: [UIFont systemFontOfSize:17 weight:UIFontWeightMedium]};
        self.navigationController.navigationBar.scrollEdgeAppearance = barScrollEdgeAppearance;
        [self.navigationController.navigationBar setTranslucent: YES];
        
    } else {
        
        self.navigationController.navigationBar.barTintColor = nil;
        [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
        self.navigationController.navigationBar.shadowImage = [UIImage new];
        [self.navigationController.navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName: SmallDecisionsThemeFontColor, NSFontAttributeName: [UIFont systemFontOfSize:17 weight:UIFontWeightMedium]}];
    }
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self tableView];
}

- (UITableView *)tableView {
    if(!_tableView) {
        NSInteger count = self.list.count + 1;
        if (self.sheetTitle.length > 0) {
           
            count += 1;
        }
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(MarginSpace, self.view.bounds.size.height, self.view.bounds.size.width - MarginSpace * 2, CellRowHeight * count + MarginSpace * 2) style:UITableViewStyleGrouped];
        _tableView.delegate   = self;
        _tableView.dataSource = self;
        _tableView.layer.cornerRadius = 10;
        _tableView.clipsToBounds = YES;
        _tableView.rowHeight     = CellRowHeight;
        _tableView.bounces       = NO;
        _tableView.scrollEnabled = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"SmallDecisionsActionSheetVCCell"];
        [_tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"SmallDecisionsActionSheetVCHeaderFooterViewCell"];
        [self.view addSubview:_tableView];
    }
    
    return  _tableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
    
    if (self.sheetTitle.length > 0) {
        
        return (section == 0) ? self.list.count + 1 : 1;
    }
    return (section == 0) ? self.list.count : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *sheetCell = [tableView dequeueReusableCellWithIdentifier:@"SmallDecisionsActionSheetVCCell" forIndexPath:indexPath];
    if (!sheetCell.selectedBackgroundView) {
        
        UIView *cellSelectedBgView = [[UIView alloc] init];
        cellSelectedBgView.backgroundColor = [SmallDecisionsSecondBgColor colorWithAlphaComponent:0.1];
        sheetCell.selectedBackgroundView = cellSelectedBgView;
    }
    sheetCell.contentView.backgroundColor = SmallDecisionsSecondBgColor;
    sheetCell.textLabel.textAlignment = NSTextAlignmentCenter;
    sheetCell.textLabel.font = SmallDecisionsSetFontSize(16);
    if (indexPath.section == 0) {
        
        NSInteger cellRow = indexPath.row;
        NSInteger sum = self.list.count;
        if (self.sheetTitle.length > 0) {
            
            sum = sum + 1;
            if (cellRow == 0) {
                
                sheetCell.selectionStyle = UITableViewCellSelectionStyleNone;
                sheetCell.textLabel.text = self.sheetTitle;
                sheetCell.textLabel.textColor = SmallDecisionsBgColor;
                sheetCell.textLabel.font      = SmallDecisionsSetFontSize(16);
            } else {
                sheetCell.selectionStyle = UITableViewCellSelectionStyleNone;
                sheetCell.textLabel.text = self.objectToTextConverter(self.list[cellRow - 1]);
                sheetCell.textLabel.textColor = SmallDecisionsThemeFontColor;
            }
        } else {
            sheetCell.selectionStyle = UITableViewCellSelectionStyleNone;
            sheetCell.textLabel.text = self.objectToTextConverter(self.list[cellRow]);
            sheetCell.textLabel.textColor = SmallDecisionsThemeFontColor;
        }
        
        if (indexPath.row == sum - 1) {

            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, -1, self.view.bounds.size.width - (MarginSpace * 2), tableView.rowHeight) byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = sheetCell.contentView.bounds;
            maskLayer.path = maskPath.CGPath;
            sheetCell.layer.mask = maskLayer;
        }
    } else {
        
        sheetCell.selectionStyle = UITableViewCellSelectionStyleNone;
        sheetCell.textLabel.text = self.cancelText;
        sheetCell.textLabel.textColor = [UIColor redColor];
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.view.bounds.size.width - (MarginSpace * 2), CellRowHeight) byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight|UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = CGRectMake(0, 0, tableView.frame.size.width, CellRowHeight);
        maskLayer.path  = maskPath.CGPath;
        sheetCell.layer.mask = maskLayer;

        sheetCell.layer.cornerRadius = 10;
        sheetCell.layer.masksToBounds = YES;
    }
    return sheetCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        if (self.sheetTitle.length > 0) {
            
            if (indexPath.row == 0) {
                
                return;
            }
            
            [SmallDecisionsNavigatorManager dismissViewControllerAnimated:YES completion:^{
                if (self.selectedBlock) {

                    self.selectedBlock(indexPath.row - 1);
                }
            }];
        } else {
            
            [SmallDecisionsNavigatorManager dismissViewControllerAnimated:YES completion:^{
                if (self.selectedBlock) {

                    self.selectedBlock(indexPath.row);
                }
            }];
        }
    } else {
        
        [SmallDecisionsNavigatorManager dismissViewControllerAnimated:YES completion:^{
            if (self.cancelBlock) {

                self.cancelBlock();
            }
        }];
    }
    [self judgeSmallDecisionsActionSheetVCWithShow:NO];
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    return MarginSpace;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SmallDecisionsActionSheetVCHeaderFooterViewCell"];
    footerView.backgroundView.backgroundColor = [UIColor clearColor];
    return footerView;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches
           withEvent:(UIEvent *)event {
    
    [self judgeSmallDecisionsActionSheetVCWithShow:NO];
    
    [SmallDecisionsNavigatorManager dismissViewControllerAnimated:YES completion:nil];
}

- (void)judgeSmallDecisionsActionSheetVCWithShow:(BOOL)show {
    
    if(show) {
        [UIView animateWithDuration:0.35 animations:^{
            if(show) {
                self.tableView.bottom = self.view.bounds.size.height  - 10;
            } else {
                self.tableView.top = self.view.bounds.size.height;
            }
        } completion:nil];
    }
}

- (BOOL)setHideNavBar {
    
    return YES;
}


@end
